﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel;
using publicLibrary;

namespace asMeishi.web.Controllers
{
    using Models;

    public class actionsController : Controller
    {
        DataSession<MongoDataContext, actions> db = new DataSession<MongoDataContext, actions>();

        //
        // GET: /growManage/
        public ActionResult Index()
        {
            setModel();
            return View();
        }

        [HttpPost]
        public ActionResult Index(FormCollection fc)
        {
            var actionEnum = (actionEnum)fc["actionEnum"].ToInt();

            actions actions = db.Get(d => d.action == actionEnum) ?? new actions() { action = actionEnum };
            var _Id = actions.Id;
            TryUpdateModel(actions);
            db.Save(actions);
            //马上刷新Application
            asMeishi.web.MvcApplication.setActionsApplication();

            return RedirectToAction("index");
        }

        void setModel()
        {
            ViewData.Model = null;

            Type type = typeof(actionEnum);
            FieldInfo[] fields = type.GetFields();

            List<actions> re = new List<actions>();
            Dictionary<actionEnum, string> reTitle = new Dictionary<actionEnum, string>();

            foreach (var item in fields)
            {
                if (item.Name == "value__") continue;

                //取得数据
                actionEnum actionEnum = (actionEnum)Enum.Parse(type, item.Name);
                actions actions = db.Get(d => d.action == actionEnum);
                re.Add(actions ?? new actions() { action = actionEnum });

                //取得特性(title)
                object[] objs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);
                DescriptionAttribute da = (DescriptionAttribute)objs[0];
                reTitle[actionEnum] = da.Description;

                /*
                string[] strEnum = new string[3];
                strEnum[1] = ((int)Enum.Parse(type, item.Name)).ToString();
                strEnum[2] = item.Name;

                object[] objs = item.GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (objs == null || objs.Length == 0)
                {
                    strEnum[0] = item.Name;
                }
                else
                {
                    DescriptionAttribute da = (DescriptionAttribute)objs[0];
                    strEnum[0] = da.Description;
                }
                re.Add(strEnum);
                */

            }

            ViewBag.enumTitle = reTitle;
            ViewData.Model = re;
        }


    }
}